package Servidor_Socket;




import java.io.*;
import java.sql.*;
import java.util.Properties;

public class Conexion {
    
	private static final String JDBC_ODBC = "jdbc:odbc:";
	private static final String CONEXION_PROPERTIES = System.getProperty("user.dir") + "\\conexion.properties";
    private static final String ODBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
	
	private String dsn, usu, pass;
    private Connection con;
    private Properties prop; 
    private File fileProperties;
    
    private static Conexion instance = null;
    
    public static Conexion getInstance(String usu,String pass) throws IOException, ClassNotFoundException{
    	if (instance == null){
    		instance = new Conexion(usu,pass);
    	}
    	return instance;
    }
    
    public Conexion(String usu,String pass) throws IOException, ClassNotFoundException { 
    	
    	loadProperties();
    	this.usu = (String) prop.getProperty("user");
    	this.pass = (String) prop.getProperty("password");
    	this.dsn = (String) prop.getProperty("dsn");
    	Class.forName(ODBC_DRIVER);
    }
    
    private void loadProperties() throws IOException{
    	fileProperties = new File(CONEXION_PROPERTIES);
    	FileInputStream fis = new FileInputStream(fileProperties);
    	prop = new Properties();
    	prop.load(fis);
    	fis.close();
    }
    
    public Connection getCon() throws SQLException {
    	if(con==null || con.isClosed()){
    		abrirConexion();
    	}
    	return con;
    }
    
    private void abrirConexion() throws SQLException {
        String url = JDBC_ODBC.concat(dsn);
        con = java.sql.DriverManager.getConnection(url,usu,pass);
    }
    
    public boolean cerrarConexion() {
        try {
            con.close();
            return true;
        } catch( java.sql.SQLException e ) { 
            return false;
        }
    }
    
    /*Script para cargar properties
    public static void main(String[] args) throws IOException {
		File file = new File("conexion.properties");
		FileOutputStream fos = new FileOutputStream(file);
		Properties prop = new Properties();
		prop.put("user", "lv2115m04");
		prop.put("password", "lv2115m04");
		prop.put("dsn", "lv2115m04");
		prop.store(fos, "Propiedades de la conexion");
	}*/
}
